package com.lb.bs.client.callback;

import com.lb.bs.client.processor.beans.ProcessorDynamicHandlerBean;
import com.lb.bs.client.processor.enums.DefaultValues;
import com.lb.bs.client.util.StringUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * program: LB-BS-Client
 * author: bsworld.xie
 * create: 2020-05-19 20:18
 * description:
 * 默认的对日志级别进行更改的工具类
 */
public class DefaultLogLevelUpdate extends UpdateCallBackService {
    private static final Logger logger = LoggerFactory.getLogger(DefaultLogLevelUpdate.class);

    @Override
    public void reloadOnKey(ProcessorDynamicHandlerBean bean) {
        String levelString = bean.getData();
        logLevelUpdate(levelString);
    }


    /**
     * 内置的支持loglevel的动态更新
     */
    public void logLevelUpdate(String levelString) {
        if (StringUtils.isNotEmpty(levelString) && DefaultValues.LogLevels.contains(levelString)) {
            Level level = Level.toLevel(levelString);
            LoggerContext context = (LoggerContext) LogManager.getContext(false);
            Configuration configuration = context.getConfiguration();
            for (Map.Entry<String, LoggerConfig> entry : configuration.getLoggers().entrySet()) {
                if (entry.getValue().getLevel().intLevel() != level.intLevel()) {
                    entry.getValue().setLevel(level);
                }
            }
            configuration.getLoggerConfig("ROOT").setLevel(level);
            context.updateLoggers(configuration);
            logger.warn("updateZkCacheValues,level:{}", levelString);
        } else {
            logger.error("updateZkCacheValues,level is empty or illegal,level:{}", levelString);
            throw new IllegalStateException("updateZkCacheValues,level is empty or illegal,level:" + levelString);
        }
    }


}
